package com.eascs.admin.o2o.back.controller;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.o2o.back.entity.O2oBackEntity;
import com.eascs.admin.o2o.back.service.O2oBackService;
import com.eascs.admin.o2o.back.vo.O2oBackVo;
import com.eascs.admin.o2o.badloan.service.O2oBadLoanService;
import com.eascs.admin.o2o.internal.util.BaseUtils;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.LoanApplyFileForm;
import com.eascs.admin.o2o.loan.entity.O2oEaLoanDataTdEnity;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanUserService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.o2o.o2ozx.serviceimpl.O2oZxServiceImpl;
import com.eascs.admin.o2o.zx.entity.O2oZxEntity;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.brand.service.O2oBrandService;
import com.eascs.brand.vo.BrandAndPartnerVo;
import com.eascs.common.doc.excel.ExcelApiHelper;
import com.eascs.common.doc.excel.RowReadHandler;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.DateUtils;
import com.eascs.common.util.IoUtil;
import com.eascs.common.util.StringUtil;
import com.eascs.common.util.UrlUtil;
import com.eascs.crm.common.entity.CustomerBasicInfoEntity;
import com.eascs.crm.common.service.ICustomerInfoService;
import com.eascs.crm.common.vo.CustomerView;
import com.eascs.crm.common.vo.QueryCustomerVO;
import com.eascs.file.FileService;
import com.eascs.file.FileTypeConstants;
import com.eascs.loan.controller.O2oPaymentsRestController;
import com.eascs.loan.entity.O2oBankLoanData;
import com.eascs.loan.form.O2oPaymentsForm;
import com.eascs.loan.service.O2oLoanService;
import com.eascs.loan.vo.O2oRepaymentRecordVo;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.PaginationRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.AjaxConfirmButton;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.sys.SysPermissionService;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.common.vo.WFRequestParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

//2)以弹窗的形式打开
@RestController
@RequestMapping("/rback")
public class O2oBackRestController extends BaseRestController {

	private static Logger log = LoggerFactory.getLogger(O2oBackRestController.class);

	@Autowired
	private O2oBackService o2oBackService;
	@Autowired
	private O2oLoanapplyService loanService;
	@Autowired
	private O2oLoanUserService o2oLoanUserService;
	@Reference
	private SysPermissionService sysPermissionService;
	@Reference(retries = 3)
	private ICustomerInfoService iCustomerInfoService;
	@Reference(retries = 3)
	private WorkFlowService workFlowService;
	@Value("${o2o.admin.newBackUrl}")
	String startUrl;
	@Autowired
	private BaseUtils baseUtils;
	@Autowired
	private O2oBrandService o2oBrandService;
	@Autowired
	private O2oLoanService o2oLoanService;
	@Autowired
	private FileService fileService;
	@Autowired
	private O2oZxServiceImpl o2oZxServiceImpl;

	/**
	 * @Description:
	 * 				<p>
	 *               审核详情显示内容
	 *               </p>
	 * @author CXW
	 * @date 2017年3月2日 上午10:47:03
	 * @version V1.0
	 */
	@RequestMapping("/loan_info")
	public BaseRestResult<String> loanInfo(String billCode, String approvalStatus) {
		O2oLoanapplyEntity loanapply = loanService.fingByBillCode(billCode);
		log.info("find billCode：{}", billCode);
		log.info("find loanapply：{}", loanapply);
		if (loanapply != null && loanapply.getLoanId() != null) {
			O2oLoanUserEntity loanUser = o2oLoanUserService.findById(loanapply.getLoanId(), loanapply.getLoanapplyNo());
			ViewContext.put("loanUser", loanUser);
		}
		BrandAndPartnerVo brand = o2oBrandService.queryCodeAndName(loanapply.getLoanapplyNo());
		O2oBankLoanData bankData = o2oLoanService.queryBillCode(loanapply.getBillCode());

		ViewContext.put("bankData", bankData);
		ViewContext.put("brand", brand);
		ViewContext.put("loanapply", loanapply);
		ViewContext.put("approvalStatus", approvalStatus);
		return new HtmlRestResult("back/loan_info");
	}

	/**
	 * @Description:
	 * 				<p>
	 *               公共方法（贷款要素内容）
	 *               </p>
	 * @author CXW
	 * @date 2017年3月2日 上午10:47:03
	 * @version V1.0
	 */
	@RequestMapping("/l_i_common")
	public BaseRestResult<String> commonLoanInfo(String loanapplyNo) {
		O2oLoanapplyEntity loanapply = loanService.findById(loanapplyNo);
		O2oLoanUserEntity loanUser = null;
		String userZxId="";
		log.info("查询贷款单号id：{}", loanapplyNo);
		log.info("查询到的对象：{}", loanapply);
		if (loanapply != null && loanapply.getLoanId() != null) {
			loanUser = o2oLoanUserService.findById(loanapply.getLoanId(), loanapply.getLoanapplyNo());
			ViewContext.put("loanUser", loanUser);
		}
		BrandAndPartnerVo brand = o2oBrandService.queryCodeAndName(loanapply.getLoanapplyNo());
		O2oBankLoanData bankData = o2oLoanService.queryBillCode(loanapply.getBillCode());
		
		if (loanUser != null) {
			userZxId = loanUser.getZxNo();
			if (userZxId != null) {
				O2oZxEntity o2oZxEntity = o2oZxServiceImpl.getEntityById(userZxId);// 征信
				ViewContext.put("o2oZxEntity", o2oZxEntity);
			}
		}
		
		ViewContext.put("bankData", bankData);
		ViewContext.put("brand", brand);
		ViewContext.put("loanapply", loanapply);
		return new HtmlRestResult("back/loan_info_common");
	}
	
	/**
	 * @Description:
	 *               <p>
	 *               跳转到修改  贷款要素  页面
	 *               </p>
	 * @author LMX
	 * @date 2017年9月6日 下午4:45:09
	 * @version V1.0
	 * @return
	 */
	@RequestMapping(value = "/l_i_commonLoan_update")
	public HtmlRestResult commonLoanInfoUpdate(String loanapplyNo) {
		O2oLoanapplyEntity loanapply = loanService.findById(loanapplyNo);
		if (loanapply != null && loanapply.getLoanId() != null) {
			O2oLoanUserEntity loanUser = o2oLoanUserService.findById(loanapply.getLoanId(), loanapply.getLoanapplyNo());
			ViewContext.put("loanUser", loanUser);
		}
		BrandAndPartnerVo brand = o2oBrandService.queryCodeAndName(loanapply.getLoanapplyNo());
		O2oBankLoanData bankData = o2oLoanService.queryBillCode(loanapply.getBillCode());

		ViewContext.put("bankData", bankData);
		ViewContext.put("brand", brand);
		ViewContext.put("loanapply", loanapply);
	
		return HtmlRestResult.popHtmlFragment("back/loan_info_common_update");
	}
	
	/**
	 * @Description:
	 *               <p>
	 *               修改  贷款要素  信息
	 *               </p>
	 * @author LMX
	 * @date 2017年9月6日 下午7:58:54
	 * @version V1.0
	 * @return
	 */
	@RequestMapping(value = "/commonLoanUpdate")
	public BaseRestResult<String> commonLoanUpdate(LoanApplyFileForm Vo) {
		if(StringUtil.isBlank(Vo.getRepayMentway())){
			 return BaseRestResult.warn("还款方式不能为空");
		}
		if(StringUtil.isBlank(Vo.getLoanTerm())){
			return BaseRestResult.warn("申请期限不能为空");
		}
		if(StringUtil.isBlank(Vo.getGuarAnteeWay())){
			return BaseRestResult.warn("担保方式不能为空");
		}
		if(StringUtil.isBlank(Vo.getReferrerName())){
			return BaseRestResult.warn("内部推荐人不能为空");
		}

		ModelResult<O2oLoanapplyEntity> modelResult = loanService.udpateEntity(Vo);
		if (!modelResult.isSuccess()) {
			 return BaseRestResult.warn("修改失败");
		}
		
		return BaseRestResult.info("修改成功").andRefresh();
	}
	
	

	@RequestMapping("/start")
	public BaseRestResult<String> startUp(O2oBackVo backVo) {
		List<O2oBackEntity> backEntitys = o2oBackService.getEntityByLoanApplyNo(backVo.getLoanApplyNo());
		O2oBackEntity backEntity = null;
		if (backEntitys != null && backEntitys.size() > 0) {
			for (O2oBackEntity o2oBackEntity : backEntitys) {
				if (o2oBackEntity.getFlowStatus().equals(StatusContexts.O2O_BANK_RUN)) {
					return BaseRestResult.warn("已经有一个流程，不能启动流程");
				} else if (o2oBackEntity.getFlowStatus().equals(StatusContexts.O2O_BANK_NEW)) {
					backEntity = o2oBackEntity;
				}
			}
		}
		O2oLoanapplyEntity loanapplyEntity = loanService.findById(backVo.getLoanApplyNo());
		if (backEntity == null) {
			O2oLoanUserEntity loanUser = o2oLoanUserService.findById(loanapplyEntity.getLoanId(), loanapplyEntity.getLoanapplyNo());
			QueryCustomerVO vo = new QueryCustomerVO();
			vo.setCustomer_id(loanapplyEntity.getLoanId());
			CustomerView customer = iCustomerInfoService.geCustomerView(vo);
			CustomerBasicInfoEntity basicInfoEntity = customer.getBasicInfo();
			backEntity = new O2oBackEntity();
			backEntity.setLoanBillcode(loanapplyEntity.getBillCode());
			backEntity.setCreateTime(new Date());
			backEntity.setLoanApplyNo(loanapplyEntity.getLoanapplyNo());
			backEntity.setLoannerAge(basicInfoEntity.getAge());
			backEntity.setLoannerName(loanUser.getUserFullName());
			backEntity.setLoannerNo(loanapplyEntity.getLoanId());
			backEntity.setLoanAmount(loanapplyEntity.getLoanaMount());
			backEntity.setFlowStatus(StatusContexts.O2O_NEW);
			backEntity.setIsDelete(StatusContexts.O2O_NO);
			backEntity.setLoanNum(o2oLoanUserService.getLoanerCount(loanapplyEntity.getLoanId()));
			int i = o2oBackService.isnert(backEntity);
			if (i > 0) {
				log.info("初始化（插入数据库成功）：【{}】条数据 ", i);
			}
		}
		ModelResult<Boolean> model = startPayBack(loanapplyEntity, backEntity);
		if (model.isSuccess()) {
			User user = UserHolder.getUser();
			backEntity.setFlowStarttime(new Date());
			backEntity.setFlowStatus(StatusContexts.O2O_BANK_RUN);
			backEntity.setEndUpdateTime(new Date());
			backEntity.setOperateName(user.getCname());
			backEntity.setOperateNo(user.getNo());
			int j = o2oBackService.update(backEntity);
			if (j > 0) {
				log.info("流程启动，更新数据库成功：【{}】条数据，贷款编号：【{}】 ", j, loanapplyEntity.getBillCode());
			}
			return BaseRestResult.info("发起成功").andRefresh();
		} else {
			log.error("发起代偿客户情况反馈流程失败，失败原因：{}", model.getDetailStack());
			return BaseRestResult.warn(model.getErrMsg());
		}
	}

	/**
	 * 启动代偿客户情况反馈流程
	 */
	public ModelResult<Boolean> startPayBack(O2oLoanapplyEntity loan, O2oBackEntity backEntity) { // 根据单号去启动流程
		ModelResult<Boolean> modelResult = new ModelResult<>();
		WFRequestParam param = new WFRequestParam();

		param.setReferId(backEntity.getId());
		param.setReferCode(loan.getBillCode());
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		param.setProcessType(ProcessTemplate.PROECESS_TYPE_DC_FED_BACK); // 启动代偿客户情况反馈流程
		User user = UserHolder.getUser();
		param.setAppliedby(user.getNo());
		param.setAppliedbyName(user.getCname());
		param.setOrgNo(loan.getLtd());
		param.setReferUrl(startUrl + "?billCode=" + loan.getBillCode() + "&loanapplyNo=" + loan.getLoanapplyNo());
		StringBuffer appliedDes = new StringBuffer("借款人:");
		appliedDes.append(loanService.findLoanUserEntity(loan.getLoanapplyNo(), loan.getLoanId()).getUserFullName());
		appliedDes.append("，放款金额:");
		java.text.DecimalFormat df=new java.text.DecimalFormat("0.00"); //格式化，保留两位小数
		BigDecimal loanAmount=new BigDecimal(0);
		if ("EA".equals(loan.getLoanType())||"FQ".equals(loan.getLoanType())) {
			loanAmount =service.findDataByBillCode(loan.getBillCode()).getLoanAmount();
		}else{
			loanAmount = o2oLoanService.queryBillCode(loan.getBillCode()).getLoanAmount();
		}
//		BigDecimal loanAmount = o2oLoanService.queryBillCode(loan.getBillCode()).getLoanAmount();
		appliedDes.append(df.format(loanAmount.doubleValue()));
		param.setAppliedDes(appliedDes.toString());
		log.info("启动代偿客户情况反馈流程，参数有贷款id：【{}】，贷款编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】，贷款摘要信息：【{}】", loan.getLoanapplyNo(), loan.getBillCode(), ProcessTemplate.SYSTEM_MODULE_O2O, param.getProcessType(), loan.getLtd(), appliedDes.toString());
		modelResult = workFlowService.instance(param);
		return modelResult;
	}

	/**
	 * @Description:
	 * 				<p>
	 *               动态表单上传文件
	 *               </p>
	 * @author CXW
	 * @date 2017年3月2日 上午10:04:08
	 * @version V1.0
	 */
	@RequestMapping("/upload_file")
	public BaseRestResult<String> uploadFile(String id, String isupload, String nodeCode) {
		String fileType = "'" + FileTypeConstants.DALIST_TYPE_HK + "','" + FileTypeConstants.DALIST_TYPE_FQHKHT + "','" + FileTypeConstants.DALIST_TYPE_FQQYZP + "'";
		PageResult<Object[]> pageResult = loanService.findO2oDataListEntityById(id, fileType);
		String titles[] = { "附件类型", "文件名", "提交人", "提交时间", "更新时间" };
		Button[] titleButtons = new Button[] { null, ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles);
		paginationInfo.setTitleButtons(titleButtons);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setBuildRowNumber(true);
		ViewContext.put("paginationInfo", paginationInfo);// 个人附件
		ViewContext.put("id", id);
		ViewContext.put("isupload", isupload);
		ViewContext.put("nodeCode", nodeCode);
		return new HtmlRestResult("back/back_file");
	}

	/**
	 * @Description:
	 * 				<p>
	 *               代偿客户情况反馈流程 信贷经理节点动态表单
	 *               </p>
	 * @author CXW
	 * @date 2017年3月2日 上午10:04:08
	 * @version V1.0
	 */
	@RequestMapping("/back_xnd")
	public BaseRestResult<String> backXnd(String referId, String nodeCode) {
		O2oBackEntity backEntity = o2oBackService.getEntityById(referId);
		ViewContext.put("backEntity", backEntity);
		ViewContext.put("nodeCode", nodeCode);
		return new HtmlRestResult("back/back_xnd");
	}

	/**
	 * @Description:
	 * 				<p>
	 *               显示动态表单内容
	 *               </p>
	 * @author CXW
	 * @date 2017年3月2日 上午10:45:30
	 * @version V1.0
	 */
	@RequestMapping("/back_xnd_view")
	public BaseRestResult<String> backXndView(String referId) {
		O2oBackEntity backEntity = o2oBackService.getEntityById(referId);
		ViewContext.put("backEntity", backEntity);
		return new HtmlRestResult("back/back_xnd_view");
	}
	@RequestMapping("/back_xnd_view_bl")
	public BaseRestResult<String> backXndViewbl(String referId, String nodeCode) {
		O2oBackEntity backEntity = o2oBackService.getEntityById(referId);
		ViewContext.put("backEntity", backEntity);
		ViewContext.put("nodeCode", nodeCode);
		return new HtmlRestResult("back/back_xnd_view_bl");
	}
	/**
	 * @Description:
	 * 				<p>
	 *               保存动态表单
	 *               </p>
	 * @author CXW
	 * @date 2017年3月2日 上午10:43:01
	 * @version V1.0
	 */
	@RequestMapping("/save_back_xnd")
	public BaseRestResult<String> saveBackXnd(O2oBackVo backVo) {
		O2oBackEntity backEntity = o2oBackService.getEntityById(backVo.getId());
		if (StringUtil.isEmpty(backVo.getLoanAssure())) {
			return BaseRestResult.warn("请选择第三方担保人");
		} else {
			backEntity.setLoanAssure(backVo.getLoanAssure());
			if (backVo.getLoanAssure().equals("Y")) {
				if (StringUtil.isEmpty(backVo.getLoannerAssure())) {
					return BaseRestResult.warn("请选择担保人与借款人关系");
				}
				backEntity.setLoannerAssure(backVo.getLoannerAssure());
			}
		}
		if (StringUtil.isEmpty(backVo.getLoanAfterMarriage())) {
			return BaseRestResult.warn("请选择贷前婚姻状况");
		} else {
			backEntity.setLoanAfterMarriage(backVo.getLoanAfterMarriage());
			if (backVo.getLoanAfterMarriage().indexOf("QT") >= 0) {
				if (!StringUtil.isEmpty(backVo.getLoanAfterMarriageOther()))
					backEntity.setLoanAfterMarriageOther(backVo.getLoanAfterMarriageOther());
				else
					return BaseRestResult.warn("请填写其他贷前婚姻状况");
			} else {
				backEntity.setLoanAfterMarriageOther("");
			}
		}
		if (StringUtil.isEmpty(backVo.getLoanBeforMarrige())) {
			return BaseRestResult.warn("请选择贷后婚姻状况");
		} else {
			backEntity.setLoanBeforMarrige(backVo.getLoanBeforMarrige());
			if (backVo.getLoanAfterMarriage().indexOf("QT") >= 0) {
				if (!StringUtil.isEmpty(backVo.getLoanAfterMarriageOther()))
					backEntity.setLoanBeforMarrigeOther(backVo.getLoanBeforMarrigeOther());
				else
					return BaseRestResult.warn("请填写其他贷后婚姻状况");
			} else {
				backEntity.setLoanBeforMarrigeOther("");
			}
		}
		if (StringUtil.isEmpty(backVo.getLoanGoal())) {
			return BaseRestResult.warn("请选择贷款目的是否实现");
		} else {
			backEntity.setLoanGoal(backVo.getLoanGoal());
		}
		if (StringUtil.isEmpty(backVo.getLoanAmountDirection())) {
			return BaseRestResult.warn("请填写贷款资金去向");
		} else {
			backEntity.setLoanAmountDirection(backVo.getLoanAmountDirection());
		}
		if (StringUtil.isEmpty(backVo.getLoanAppeal())) {
			return BaseRestResult.warn("请选择诉讼情况");
		} else {
			backEntity.setLoanAppeal(backVo.getLoanAppeal());
			if (backVo.getLoanAppeal().equals("Y")) {
				if (StringUtil.isEmpty(backVo.getLoanAppealCont())) {
					return BaseRestResult.warn("请填写诉讼内容");
				}
				backEntity.setLoanAppealCont(backVo.getLoanAppealCont());
			} else {
				backEntity.setLoanAppealCont("");
			}
		}
		if (StringUtil.isEmpty(backVo.getLoanSd())) {
			return BaseRestResult.warn("请选择SD数据提供");
		} else {
			backEntity.setLoanSd(backVo.getLoanSd());
		}
		if (StringUtil.isEmpty(backVo.getLoanStore())) {
			return BaseRestResult.warn("请选择门店经营情况");
		} else {
			backEntity.setLoanStore(backVo.getLoanStore());
			if (backVo.getLoanStore().indexOf("QT") >= 0) {
				if (!StringUtil.isEmpty(backVo.getLoanStoreInfo()))
					backEntity.setLoanStoreInfo(backVo.getLoanStoreInfo());
				else
					return BaseRestResult.warn("请填写其他门店经营情况");
			} else {
				backEntity.setLoanStoreInfo("");
			}
		}
		if (StringUtil.isEmpty(backVo.getLoanProperty())) {
			return BaseRestResult.warn("请选择资产情况");
		} else {
			backEntity.setLoanProperty(backVo.getLoanProperty());
			if (backVo.getLoanProperty().indexOf("QT") >= 0) {
				if (!StringUtil.isEmpty(backVo.getLoanPropertyInfo()))
					backEntity.setLoanPropertyInfo(backVo.getLoanPropertyInfo());
				else
					return BaseRestResult.warn("请填写其他资产情况");
			} else {
				backEntity.setLoanPropertyInfo("");
			}
		}
		if (StringUtil.isEmpty(backVo.getHomeIncome())) {
			return BaseRestResult.warn("请选择家庭生活收入来源");
		} else {
			backEntity.setHomeIncome(backVo.getHomeIncome());
			if (backVo.getHomeIncome().indexOf("QT") >= 0) {
				if (!StringUtil.isEmpty(backVo.getHomeIncomeInfo()))
					backEntity.setHomeIncomeInfo(backVo.getHomeIncomeInfo());
				else
					return BaseRestResult.warn("请填写其他家庭生活收入来源");
			} else {
				backEntity.setHomeIncomeInfo("");
			}
		}
		if (StringUtil.isEmpty(backVo.getLoanAfterLiabilities())) {
			return BaseRestResult.warn("请选择贷前家庭总负债");
		} else {
			backEntity.setLoanAfterLiabilities(backVo.getLoanAfterLiabilities());
			if (backVo.getLoanAfterLiabilities().indexOf("QT") >= 0) {
				if (!StringUtil.isEmpty(backVo.getLoanAfterLiabilitiesInfo()))
					backEntity.setLoanAfterLiabilitiesInfo(backVo.getLoanAfterLiabilitiesInfo());
				else
					return BaseRestResult.warn("请填写其他贷前家庭总负债");
			} else {
				backEntity.setLoanAfterLiabilitiesInfo("");
			}
		}
		if (StringUtil.isEmpty(backVo.getLoanBeforeLiabilities())) {
			return BaseRestResult.warn("请选择贷后家庭总负债");
		} else {
			backEntity.setLoanBeforeLiabilities(backVo.getLoanBeforeLiabilities());
			if (backVo.getLoanBeforeLiabilities().indexOf("QT") >= 0) {
				if (!StringUtil.isEmpty(backVo.getLoanBeforeLiabilitiesInfo()))
					backEntity.setLoanBeforeLiabilitiesInfo(backVo.getLoanBeforeLiabilitiesInfo());
				else
					return BaseRestResult.warn("请填写其他贷后家庭总负债");
			} else {
				backEntity.setLoanBeforeLiabilitiesInfo("");
			}
		}
		if (StringUtil.isEmpty(backVo.getOtherLiabilities())) {
			return BaseRestResult.warn("请选择其他负债催收情况");
		} else {
			backEntity.setOtherLiabilities(backVo.getOtherLiabilities());
		}
		if (StringUtil.isEmpty(backVo.getHomeLive())) {
			return BaseRestResult.warn("请选择家庭成员居住情况");
		} else {
			backEntity.setHomeLive(backVo.getHomeLive());
			if (backVo.getHomeLive().indexOf("QT") >= 0) {
				if (!StringUtil.isEmpty(backVo.getHomeLive()))
					backEntity.setHomeLiveOther(backVo.getHomeLiveOther());
				else
					return BaseRestResult.warn("请填写其他家庭成员居住情况");
			} else {
				backEntity.setHomeLiveOther("");
			}
		}
		if (StringUtil.isEmpty(backVo.getForeignInvestment())) {
			return BaseRestResult.warn("请选择对外投资情况");
		} else {
			backEntity.setForeignInvestment(backVo.getForeignInvestment());
			if (backVo.getForeignInvestment().indexOf("QT") >= 0) {
				if (!StringUtil.isEmpty(backVo.getForeignInvestmentOther()))
					backEntity.setForeignInvestmentOther(backVo.getForeignInvestmentOther());
				else
					return BaseRestResult.warn("请填写其他对外投资情况");
			} else {
				backEntity.setForeignInvestmentOther("");
			}
		}
		if (StringUtil.isEmpty(backVo.getLoanClientDescription())) {
			return BaseRestResult.warn("请填写客户贷款审批时整体情况描述");
		} else {
			backEntity.setLoanClientDescription(backVo.getLoanClientDescription());
		}
		if (StringUtil.isEmpty(backVo.getPresentDecription())) {
			return BaseRestResult.warn("请填写客户当前整体情况描述");
		} else {
			backEntity.setPresentDecription(backVo.getPresentDecription());
		}
		if (StringUtil.isEmpty(backVo.getBadloanDescription())) {
			return BaseRestResult.warn("请填写代偿原因描述");
		} else {
			backEntity.setBadloanDescription(backVo.getBadloanDescription());
		}
		if (StringUtil.isEmpty(backVo.getRevisitDate())) {
			return BaseRestResult.warn("请选择回访时间");
		} else {
			backEntity.setRevisitDate(backVo.getRevisitDate());
		}
		if (StringUtil.isEmpty(backVo.getIsSignContract())) {
			return BaseRestResult.warn("请选择是否能在签订分期合同前结清全部利息");
		} else {
			backEntity.setIsSignContract(backVo.getIsSignContract());
		}
		if (StringUtil.isEmpty(backVo.getIsSignLoan())) {
			return BaseRestResult.warn("请选择是否能在签订分期合同前偿还部分代偿");
		} else {
			backEntity.setIsSignLoan(backVo.getIsSignLoan());
		}
		if (StringUtil.isEmpty(backVo.getIsFirstSign())) {
			return BaseRestResult.warn("请选择是否能在签订分期合同前支付第一期分期款");
		} else {
			backEntity.setIsFirstSign(backVo.getIsFirstSign());
		}
		if (StringUtil.isEmpty(backVo.getIsWillReloan())) {
			return BaseRestResult.warn("请选择是否有还款意愿");
		} else {
			backEntity.setIsWillReloan(backVo.getIsWillReloan());
		}
		if (StringUtil.isEmpty(backVo.getUpDate())) {
			return BaseRestResult.warn("请选择上门时间");
		} else {
			backEntity.setUpDate(backVo.getUpDate());
		}
		if (StringUtil.isEmpty(backVo.getStagesAmount())) {
			return BaseRestResult.warn("请填写分期本金金额");
		} else {
			backEntity.setStagesAmount(backVo.getStagesAmount());
		}
		if (StringUtil.isEmpty(backVo.getStagesTerm())) {
			return BaseRestResult.warn("请选择分期期限");
		} else {
			backEntity.setStagesTerm(backVo.getStagesTerm());
		}
		if (StringUtil.isEmpty(backVo.getStagesPlan())) {
			return BaseRestResult.warn("请填写分期还款计划");
		} else {
			backEntity.setStagesPlan(backVo.getStagesPlan());
		}
		if (StringUtil.isEmpty(backVo.getStagesRate())) {
			return BaseRestResult.warn("请填写分期利率");
		} else {
			backEntity.setStagesRate(backVo.getStagesRate());
		}
		if (StringUtil.isEmpty(backVo.getAssureStep())) {
			return BaseRestResult.warn("请填写担保措施");
		} else {
			backEntity.setAssureStep(backVo.getAssureStep());
		}
		int count = o2oBackService.getCountPlan(backVo.getId());
		if (count <= 0) {
			return BaseRestResult.warn("请填先上传分期还款计划");
		}
//		if (isUploadFile(backVo.getId())) {
			int i = o2oBackService.update(backEntity);
			if (i > 0) {
				return BaseRestResult.info("保存成功");
			} else {
				return BaseRestResult.warn("保存失败");
			}
//		} else {
//			return BaseRestResult.warn("请上传代偿情况反馈资料附件");
//		}
	}
	/**
	 * 代偿情况反馈资料
	 * @param loanapplyNo
	 * @return
	 */
	public boolean isUploadFile(String loanapplyNo) {
		String fileType = "'" + FileTypeConstants.DALIST_TYPE_HK + "'";
		int i = fileService.getBackDataList(loanapplyNo, fileType);
		if (i > 0) {
			return false;
		} else {
			return true;
		}
	}
	public boolean isUploadFileall(String loanapplyNo) {
		String fileType = "'" + FileTypeConstants.DALIST_TYPE_HK + "','" + FileTypeConstants.DALIST_TYPE_FQHKHT + "','" + FileTypeConstants.DALIST_TYPE_FQQYZP + "'";
		int i = fileService.getBackDataList(loanapplyNo, fileType);
		if (i < 3) {
			return false;
		} else {
			return true;
		}
	}
	/**
	 * @Description:
	 * 				<p>
	 *               待审核页面
	 *               </p>
	 * @author CXW
	 * @date 2017年3月2日 上午11:08:10
	 * @version V1.0
	 */
	@RequestMapping("/approl")
	public BaseRestResult<String> recordView(O2oRepaymentRecordVo entity) {
		log.info("工作流访问回款详情：参数billCode：【{}】，referId:【{}】", entity.getBillCode(), entity.getReferId());
		String approvalUrl = baseUtils.getApprovalUrl(entity.getNodeAuditorId(), ProcessTemplate.SYSTEM_MODULE_O2O);// 审批代办列表详情URL
		ViewContext.put("approvalUrl", approvalUrl);
		String agreeUrl = baseUtils.getApprovalAgreeUrl(entity.getReferId(), entity.getNodeAuditorId(), ProcessTemplate.SYSTEM_MODULE_O2O);
		ViewContext.put("agreeUrl", agreeUrl);
		ViewContext.put("billCode", entity.getBillCode());
		ViewContext.put("nodeCode", entity.getNodeCode());
		ViewContext.put("approvalStatus", entity.getApprovalStatus());
		return HtmlRestResult.popHtmlFragment("back/approl");
	}

	/**
	 * @Description:
	 * 				<p>
	 *               详情页面代偿分期
	 *               </p>
	 * @author CXW
	 * @date 2017年3月2日 下午5:35:32
	 * @version V1.0
	 */
	@RequestMapping("/loan_list")
	public PaginationRestResult findLoanDC(String loanapplyNo) {
		String findurl = "/rback/loan_list";
		findurl = UrlUtil.appendUrl(findurl, "loanapplyNo", loanapplyNo);
		PageResult<Object[]> pageResult = o2oBackService.getO2oBackEntitys(loanapplyNo);
		String titles[] = { "贷款单号", "创建时间", "提交人", "诉讼情况" };
		SelectDataOption[] selectDataOptions = { null, null, null, new SelectDataOption("ASSURE") };
		Button[] titleButtons = new Button[] { ButtonHelper.createOpenButton(null, "/back/detail?backId=") };
		PaginationInfo o2oPagingInfo = new PaginationInfo(pageResult, titles, findurl);
		o2oPagingInfo.setSelectDataOptions(selectDataOptions);
		o2oPagingInfo.setFirstRenderColumnIndex(1);
		o2oPagingInfo.setTitleButtons(titleButtons);
		o2oPagingInfo.setRendTo("#result_list");
		return PaginationRestResult.buildPaginationRestResult(o2oPagingInfo);
	}

	/**
	 * @Description:
	 * 				<p>
	 *               代偿放款信贷经理动态表单导入还款计划
	 *               </p>
	 * @author CXW
	 * @date 2017年3月15日 上午11:22:37
	 * @version V1.0
	 */
	@RequestMapping("/uploanBackPlan")
	public BaseRestResult<String> uploadBankExcel(@RequestParam(value = "file", required = false) MultipartFile file, String billCode, String mainId) {
		InputStream inputStream = null;
		try {
			inputStream = file.getInputStream();
			/** 获取文件的后缀 **/
			String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			if (!".xls".equals(suffix)) {
				return BaseRestResult.warn("文件类型不对，请下载还款计划模板");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		User user = UserHolder.getUser();
		String loanerName = user.getCname();
		try {
			ExcelApiHelper.readHandle(inputStream, new RowReadHandler() {
				@Override
				public void handle(int sheetIndex, int rowIndex, Object[] rowDatas) {
					check(sheetIndex, rowIndex, rowDatas, 0, billCode, loanerName, mainId);
				}
			});
		} catch (RuntimeException e) {
			String message = e.getMessage();
			message = e.getMessage().substring(27, message.length());
			return BaseRestResult.warn(message);
		}
		InputStream inputStream1 = null;
		try {
			inputStream1 = file.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			ExcelApiHelper.readHandle(inputStream1, new RowReadHandler() {
				@Override
				public void handle(int sheetIndex, int rowIndex, Object[] rowDatas) {
					check(sheetIndex, rowIndex, rowDatas, 1, billCode, loanerName, mainId);
				}
			});

		} catch (RuntimeException e) {
			String message = e.getMessage();
			message = e.getMessage().substring(27, message.length());
			return BaseRestResult.warn(message);

		}
		return BaseRestResult.buildClosestReloadResult();
	}

	/**
	 * @Description:
	 * 				<p>
	 *               校验代偿分期导入计划数据
	 *               </p>
	 * @author CXW
	 * @date 2017年3月15日 下午1:38:15
	 * @version V1.0
	 */
	private void check(int sheetIndex, int rowIndex, Object[] rowDatas, int type, String billCode, String name, String mainId) {

		String periods = "";
		String paymentsDate = "";
		String residualPrincipal = "";
		String payPrincipal = "";
		String payInterest = "";
		if (sheetIndex == 0 && rowIndex > 0) {
			String message = "第" + rowIndex + "行：";
			if (StringUtil.isEmpty(billCode) && StringUtil.isEmpty(name)) {
				throw new RuntimeException("贷款单号、借款人姓名两者必须有一个");
			}
			for (int i = 0; i < rowDatas.length; i++) {
				if (i == 0) {
					periods = String.valueOf(rowDatas[0] == null ? "" : rowDatas[0]);
				} else if (i == 1) {
					paymentsDate = String.valueOf(rowDatas[1] == null ? "" : rowDatas[1]);
				} else if (i == 2) {
					residualPrincipal = String.valueOf(rowDatas[2] == null ? "" : rowDatas[2]);
				} else if (i == 3) {
					payPrincipal = String.valueOf(rowDatas[3] == null ? "" : rowDatas[3]);
				} else if (i == 4) {
					payInterest = String.valueOf(rowDatas[4] == null ? "" : rowDatas[4]);
				}
			}
			// 如果单款单号不为空，则查看是否存在，如果存在，则取出借款姓名、证件号码

			if (periods == null || "".equals(periods)) {
				throw new RuntimeException(message + "期数不能为空");
			}

			if (paymentsDate == null || "".equals(paymentsDate)) {
				throw new RuntimeException(message + "计划还款时间不能为空");
			}
			if (residualPrincipal == null || "".equals(residualPrincipal)) {
				throw new RuntimeException(message + "剩余本金不能为空");
			}
			if (payPrincipal == null || "".equals(payPrincipal)) {
				throw new RuntimeException(message + "计划还款本金不能为空");
			}
			if (payInterest == null || "".equals(payInterest)) {
				throw new RuntimeException(message + "计划还款利息不能为空");
			}
			if (!isDouble(periods)) {
				throw new RuntimeException(message + "期数格式不正确");
			}
			if (!isValidDate(paymentsDate)) {
				throw new RuntimeException(message + "计划还款时间格式不正确");
			}
			if (!isDouble(residualPrincipal)) {
				throw new RuntimeException(message + "剩余本金格式不正确");
			}
			if (!isDouble(payPrincipal)) {
				throw new RuntimeException(message + "计划还款本金格式不正确");
			}
			if (!isDouble(payInterest)) {
				throw new RuntimeException(message + "计划还款利息格式不正确");
			}
			long num = Math.round(Double.parseDouble(periods));
			// 数据插入
			if (type == 1) {
				O2oEaLoanDataTdEnity dataTdEnity = new O2oEaLoanDataTdEnity();
				dataTdEnity.setDataType("2");
				dataTdEnity.setIsDel("N");
				dataTdEnity.setMainId(mainId);
				dataTdEnity.setOpratePsn(name);
				dataTdEnity.setOprateTime(new Date());
				dataTdEnity.setPayInterest(new BigDecimal(payInterest));
				dataTdEnity.setPaymentsDate(new java.sql.Date(DateUtils.formateStandDate(paymentsDate).getTime()));
				dataTdEnity.setPayPrincipal(new BigDecimal(payPrincipal));
				dataTdEnity.setPayTotal(new BigDecimal(payPrincipal).add(new BigDecimal(payInterest)));
				dataTdEnity.setPeriods(num);
				dataTdEnity.setRepaymentStatus("JQ");
				dataTdEnity.setResidualPrincipal(new BigDecimal(residualPrincipal));
				dataTdEnity.setPayType("由计划表导入");
				int i = service.insert(dataTdEnity);
				if (i < 0) {
					throw new RuntimeException(message + "数据库保存异常");
				}
			}
		}
	}

	@Autowired
	private O2oBadLoanService service;

	/**
	 * @Title: isDouble
	 * @Description: 判断是否为double类型
	 * @author CXW
	 * @param str
	 * @return
	 * @return boolean
	 * @throws @date
	 *             2017年3月15日 下午1:38:15
	 */
	private boolean isDouble(String str) {
		boolean flag = true;
		try {
			Double.parseDouble(str);
		} catch (Exception e) {
			flag = false;
		}
		return flag;
	}

	/**
	 * @Description:
	 * 				<p>
	 *               校验日期格式是否为：yyyy-MM-dd
	 *               </p>
	 * @author CXW
	 * @date 2017年3月15日 下午1:40:33
	 * @version V1.0
	 */
	private boolean isValidDate(String str) {
		DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date date = (Date) formatter.parse(str);
			return str.equals(formatter.format(date));
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * @Description:
	 * 				<p>
	 *               下载代偿分期分期还款计划模板
	 *               </p>
	 * @author CXW
	 * @date 2017年3月15日 下午2:07:54
	 * @version V1.0
	 */
	@RequestMapping("/download")
	public BaseRestResult<String> dowanload(HttpServletResponse httpServletResponse, HttpServletRequest request) {
		BaseRestResult<String> result = null;
		String file = O2oPaymentsRestController.class.getResource("/excelTemplate/back_plan.xls").getPath();
		OutputStream os = null;
		try {
			String outfile = "分期还款计划.xls";
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			File f = new File(file);
			if (!f.exists())
				throw new RuntimeIOException("file not found");
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
			os.write(byteArrayOutputStream.toByteArray());
			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
		return result;
	}

	/**
	 * @Description:
	 * 				<p>
	 *               加载分期还款计划
	 *               </p>
	 * @author CXW
	 * @date 2017年3月15日 下午2:19:19
	 * @version V1.0
	 */
	@RequestMapping("/back_plan")
	public BaseRestResult<String> backPlan(String billCode, String mainId, String uploadType) {
		O2oPaymentsForm o2oPaymentsForm = new O2oPaymentsForm();
		o2oPaymentsForm.setBillCode(mainId);
		o2oPaymentsForm.setPageSize(100);
		PageResult<Object[]> pageResult = service.backPlan(o2oPaymentsForm);
		String[] titles = { "还款期数", "应还款日期", "剩余本金", "应还本金", "应还利息" };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(1);
		AjaxConfirmButton[] dealButton = new AjaxConfirmButton[] { new AjaxConfirmButton("删除", "/rbadloan/delPayments?payments_id=") };
		paginationInfo.setMoreButtons(dealButton);
		paginationInfo.setFormats(new Format[] { null, null, new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00") });
		ViewContext.put("paginationInfo", paginationInfo);
		ViewContext.put("mainId", mainId);
		ViewContext.put("billCode", billCode);
		ViewContext.put("uploadType", uploadType);
		return new HtmlRestResult("back/back_plan");
	}
	
	/**
	 * 点击贷款单号以弹窗的形式打开详情ajax页面
	 * @param backId
	 * @return
	 */
	@RequestMapping("/detail")
	public BaseRestResult<String> detail(String backId) {
		O2oBackEntity backEntity = o2oBackService.getEntityById(backId);
		String agreeUrl = baseUtils.getApprovalAgreeUrl(backId, null, ProcessTemplate.SYSTEM_MODULE_O2O);
		ViewContext.put("agreeUrl", agreeUrl);
		ViewContext.put("referId", backId);
		ViewContext.put("billCode", backEntity.getLoanBillcode());
		//return "back/detail";
		return HtmlRestResult.popHtmlFragment("back/detail");//3)以弹窗的形式打开
	}
	
	/**
	 * @Description:
	 * 				<p>
	 *               代偿反馈查询 详情中的底部按钮  
	 *               </p>
	 * @author LMX
	 * @date 2017年6月6日
	 * @version V1.0
	 */
	@RequestMapping("/buttons")
	public BaseRestResult<String> bottons(String id) {
		O2oBackEntity o2oBackEntity = o2oBackService.getEntityById(id);

		List<Button> bottons = new ArrayList<>();
		if (o2oBackEntity != null) {
			if (!StringUtils.isEmpty(o2oBackEntity.getFlowStatus()) ) {
				
				if ("NEW".equals(o2oBackEntity.getFlowStatus() ) ) {
						bottons.add(ButtonHelper.createAjaxConfirmButton("启动代偿分期", "/rback/start?loanApplyNo="+ o2oBackEntity.getLoanApplyNo(), "startBack"));
				}
				
			}
		}
		ViewContext.put("buttons", bottons);
		ViewContext.put("entity", o2oBackEntity);
		return new HtmlRestResult("generation/detail_button");
	}
	
}
